package com.zhenyi.core.wechat.bridge;

import java.util.HashMap;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.utils.AESUtils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;

public final class WXTools {

	private WXTools() {
	}

	private static final String AES_KEY = "zhenyikejiweixin";
	private static final String HOST = "http://wechatopen.cenjiawen.com/file/trans";

	public static String deData(String data) {
		String de = AESUtils.decrypt(AES_KEY, data);
		if (de == null) {
			LogKit.warn("decrypt fail");
		}
		return de;
	}

	public static String enData(String data) {
		return AESUtils.encrypt(AES_KEY, data);
	}

	public static boolean verify(String json, String sign) {
		if (StrKit.notBlank(json)) {
			return sign.equals(sign(json));
		}
		return false;
	}

	public static String sign(String data) {
		String content = AESUtils.encrypt(AES_KEY, data);
		Digester md5 = new Digester(DigestAlgorithm.MD5);
		String digestHex = md5.digestHex(content);
		return digestHex;
	}

	private static String request(String url, String body, String method) {
		String nonce = RandomUtil.randomNumbers(10);
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("url", url);
		paramMap.put("body", body);
		paramMap.put("method", method);
		paramMap.put("nonce", nonce);
		String json = JsonKit.toJson(paramMap);
		String en = enData(json);
		HashMap<String, Object> data = new HashMap<>();
		String sign = sign(en);
		data.put("sign", sign);
		data.put("data", en);
		String response = HttpUtil.post(HOST, data);
		JSONObject result = new JSONObject(response);
		JSONObject info = result.getJSONObject("info");
		String resultData = info.getStr("data");
		String resultSign = info.getStr("sign");
		if (!verify(resultData, resultSign)) {
			return null;
		}
		String rawData = deData(resultData);
		return rawData;

	}

	/**
	 * 微信post
	 * 
	 * @param url
	 * @param body
	 * @return
	 */
	public final static String request(String url, String body) {
		return request(url, body, "POST");
	}

	/**
	 * 微信post
	 * 
	 * @param url
	 * @param body
	 * @return
	 */
	public final static String post(String url, String body) {
		return request(url, body, "POST");
	}

	/**
	 * 微信get
	 * 
	 * @param url
	 * @return
	 */
	public final static String get(String url) {
		return request(url, "", "GET");
	}

}
